package config

import (
	"fmt"
	"os"

	"gopkg.in/yaml.v2"
)

type Config struct {
	Databases []Database `yaml:"databases"`
}

type Database struct {
	Name     string `yaml:"name"`
	User     string `yaml:"user"`
	Host     string `yaml:"host"`
	Password string `yaml:"password"`
	Database string `yaml:"database"`
	Table    string `yaml:"table"`
}

func (d *Database) GetDSN() string {
	if d.Name == "" {
		return ""
	}
	return fmt.Sprintf("%s:%s@tcp(%s)/%s?parseTime=true", d.User, d.Password, d.Host, d.Database)
}

func (d *Database) GetRow() string {
	// 实例：ynyx-bbdctr-test | DSN: 10.202.216.185:3306/bbdctr | 数据表: flyway_schema_history_bbdctr
	return fmt.Sprintf("实例：%s | DSN: %s:%s/%s | 数据表: %s", d.Name, d.Host, d.User, d.Database, d.Table)
}

func (d *Database) GetTableName() string {
	return d.Table
}

func LoadConfig(filename string) (*Config, error) {
	data, err := os.ReadFile(filename)
	if err != nil {
		return nil, err
	}

	var cfg Config
	err = yaml.Unmarshal(data, &cfg)
	if err != nil {
		return nil, err
	}

	return &cfg, nil
}
